﻿using System;
using interop = System.Runtime.InteropServices;

namespace Co9320.NamaAlert.Engine.DebugHelper
{
	internal static class ConsoleControl
	{
		private const int STD_INPUT_HANDLE = -10;
		private const int STD_OUTPUT_HANDLE = -11;
		private const int STD_ERROR_HANDLE = -12;

		private static readonly IntPtr OutputHandle;

		static ConsoleControl()
		{
			AllocConsole();
			IntPtr h = GetStdHandle(STD_OUTPUT_HANDLE);
			OutputHandle = h;
		}

		public static void WriteLine(string Value)
		{
			if (Value == null)
			{
				return;
			}

			int s = 0;
			WriteConsole(OutputHandle, Value, Value.Length, out s, IntPtr.Zero);
			WriteConsole(OutputHandle, "\r\n", 2, out s, IntPtr.Zero);
		}

		public static void WriteLine()
		{
			WriteLine("");
		}

		public static void WriteLine(string format, params object[] args)
		{
			WriteLine(string.Format(format, args));
		}

		public static void WriteLine(object Value)
		{
			WriteLine(Value.ToString());
		}

		[interop::DllImport("kernel32.dll")]
		private static extern int AllocConsole();

		[interop::DllImport("kernel32.dll")]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		[interop::DllImport("kernel32.dll", CharSet = interop::CharSet.Auto)]
		private static extern int WriteConsole(IntPtr hConsoleOutput,
			string Buffer, int Size, out int WrittenSize,
			IntPtr lpResrved);

	}
}
